<template>
    <div class="menu-wrapper">
        <el-form ref="couponForm" :model="form" label-width="100px">
            <el-form-item label="活动名称" prop="name" :rules="{ required: true, message: '请输入名称', trigger: 'blur' }">
                <el-col :span="12">
                    <el-input style="width:400px" placeholder="例:满100减30" v-model="form.name" />
                </el-col>
            </el-form-item>
            <el-form-item label="活动描述">
                <el-col :span="12">
                    <el-input style="width:400px" v-model="form.introduction" />
                </el-col>
            </el-form-item>
            <el-form-item label="起止日期"  prop="dateTime" :rules="{ required: true, message: '请选择起止日期', trigger: 'blur' }">
                <el-col :span="12">
                    <el-date-picker style="width:400px" v-model="form.dateTime" type="datetimerange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
                    </el-date-picker>
                </el-col>
            </el-form-item>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="适用场景" prop="scope" :rules="{ required: true, message: '请选择适用范围', trigger: 'blur' }">
                        <el-select style="width:200px" v-model="form.scope" placeholder="请选择">
                            <el-option label="全场" value="0" />
                            <el-option label="店内" value="1" />
                            <el-option label="商城" value="2" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-tabs>
                <!--tab1-->
                <el-tab-pane label="优惠信息">
                    <el-row>
                        <el-col :span="12" v-if="form.targetType!=5">
                            <el-form-item label="优惠类型" prop="type" :rules="{ required: true, message: '请选择优惠类型', trigger: 'blur' }">
                                <el-select style="width:200px" v-model="form.type" placeholder="请选择" @change="typeChange">
                                    <el-option label="满减" value="0" />
                                    <el-option label="满折" value="1" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="12" v-if="form.targetType!=5">
                            <el-form-item label="使用门槛" prop="minimumPrice" :rules="{ required: true, message: '请输入使用门槛', trigger: 'blur' }">
                                <el-input style="width:200px" type="number" @mousewheel.native.prevent @DOMMouseScroll.native.prevent placeholder="消费满多少元可用" v-model="form.minimumPrice" />
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col :span="12">
                            <el-form-item label="兑换产品" prop="productId" :rules="{ required: true, message: '请选择可兑换产品', trigger: 'blur' }" v-if="form.targetType==5">
                                <!--可搜索带选择框-->
                                <el-select style="width:400px" v-model="form.productId" filterable remote placeholder="请输入商品关键字" :filter-method="searchProduct" :loading="productLoading">
                                    <el-option v-for="item in productOptions" :key="item.id" :label="item.name" :value="item.id">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row>
                        <el-col v-if="form.type==2||form.targetType==5">
                            <el-form-item label="兑换数量" prop="quantity" :rules="{ required: true, message: '请输入数量', trigger: 'blur' }">
                                <el-col :span="12">
                                    <el-input style="width:200px" type="number" @mousewheel.native.prevent @DOMMouseScroll.native.prevent v-model="form.quantity" />
                                </el-col>
                            </el-form-item>
                        </el-col>
                    </el-row>

                  <el-row>
                    <el-col v-if="form.targetType==5">
                      <el-form-item label="补运费">
                        <el-col :span="12">
                          <el-input style="width:200px" type="number" @mousewheel.native.prevent @DOMMouseScroll.native.prevent v-model="form.amount" />
                        </el-col>
                      </el-form-item>
                    </el-col>


                  </el-row>
                </el-tab-pane>
                <el-tab-pane label="投放">
                    <el-row>
                        <el-col>
                            <el-form-item label="投放方式" prop="mode" :rules="{ required: true, message: '请选择投放方式', trigger: 'blur' }">
                                <el-col :span="12">
                                    <el-select style="width:200px" v-model="form.mode" placeholder="请选择">
                                        <el-option label="自由领取" value="0" />
                                        <el-option label="活动投放" value="1" />
                                    </el-select>
                                </el-col>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col>
                            <el-form-item label="发行张数" prop="stock" :rules="{ required: true, message: '请输入发行张数', trigger: 'blur' }">
                                <el-col :span="12">
                                    <el-input style="width:200px" type="number" @mousewheel.native.prevent @DOMMouseScroll.native.prevent v-model="form.stock" />
                                </el-col>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col v-if="form.mode==0||form.targetType==5">
                            <el-form-item :label="form.targetType==0||form.targetType==5?'月限用量':'每人限领'" prop="maxgiven" :rules="{ required: true, message: '请输入每人限领', trigger: 'blur' }">
                                <el-col :span="12">
                                    <el-input style="width:200px" type="number" @mousewheel.native.prevent @DOMMouseScroll.native.prevent placeholder="0表示不限张数" v-model="form.maxgiven" />
                                </el-col>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-tab-pane>
            </el-tabs>
            <el-form-item>
                <el-col :span="12">
                    <el-button type="primary" :loading="clicked" @click="saveCoupon('couponForm')">
                        &nbsp&nbsp&nbsp&nbsp完 成&nbsp&nbsp&nbsp&nbsp
                    </el-button>
                </el-col>
            </el-form-item>
        </el-form>

    </div>
</template>
<style scoped>
.menu-wrapper {
    margin: 15px;
}
.dialog-button-slot {
    width: 100%;
    padding-top: 20px;
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-end;
}
</style>
<script>
import productTable from "../../../components/ProductList/productList";
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
import { EventBus } from "@/api/eventBus";
import utils from "../../../utils/utils.js";
import { find, update } from "@/api/coupon";
import { list as brandList } from "@/api/brand";
import { list as productList } from "@/api/product";
import { list as productCategoryList } from "@/api/productCategory";
import { list as memberList } from "@/api/member";
export default {
    name: "exchange-edit",
    directives: { elDragDialog },
    filters: {},
    components: { productTable },
    data() {
        return {
            clicked: false, // 按钮防双击
             form: {
                id: "",
                name: "",
                amount: 0,
                beginDate: "",
                endDate: "",
                introduction: "",
                productId: "",
                maxgiven: 1,
                minimumPrice: "",
                targetType: 5,
                targets: [],
                mode: 0,
                quantity: 1,
                scope: "",
                stock: 0,
                subType: 0,
                type: "0",
                dateTime: [],
            },
            vips: [],
            typeList: [],
            isProduct: false,
            productLoading: false,
            productOptions: [],
            vipOptions: [
                { id: 0, name: "vip1" },
                { id: 1, name: "vip2" },
                { id: 2, name: "vip3" },
                { id: 3, name: "vip4" },
                { id: 4, name: "vip5" },
            ],
            typeId: "0",
        };
    },
    created() {
        this.loadProduct("");
        this.getData();
    },
    watch: {
        // 路由地址不变的情况下,如果id变化则重新获取数据
        $route(newVal, oldVal) {
            console.log(newVal);
            if (newVal.name == "coupon-edit" && newVal.query.id != this.id) {
                this.getData();
            }
        },
    },
    methods: {

        getData() {
            this.form.id = this.$route.query.id;
            this.products = [];
            find(this.form.id)
                .then((response) => {
                    response.data.coupon.dateTime = [];
                    response.data.coupon.dateTime.push(
                        response.data.coupon.beginDate
                    );
                    response.data.coupon.dateTime.push(
                        response.data.coupon.endDate
                    );
                    this.form = response.data.coupon;
                    this.form.scope = JSON.stringify(this.form.scope);
                    this.form.type = JSON.stringify(this.form.type);
                    this.form.mode = JSON.stringify(this.form.mode);
                    this.typeList = [];
                    this.form.targets.forEach((item) => {
                        let couponTarget = {
                            id: item.targetId,
                            name: item.targetName,
                            tabId: item.productType,
                        };
                        this.typeList.push(couponTarget);
                    });

                })
                .catch((error) => {});
        },

        typeChange(id) {
            this.typeId = id;
            if (id === "2" || id === "3") {
                this.isProduct = true;
            } else {
                this.isProduct = false;
            }
        },

        loadProduct(query) {
            let params = new URLSearchParams();
            params.append("pageNum", 1);
            params.append("pageSize", 50);
            params.append("name", query);
            this.productLoading = true;
            productList(params)
                .then((response) => {
                    this.productLoading = false;
                    this.productOptions = response.data.data;
                })
                .catch((error) => {
                    this.productLoading = false;
                });
        },
        searchProduct(query) {
            this.loadProduct(query);
        },

        saveCoupon(form) {
            const _this = this;
            this.$refs[form].validate((valid) => {
                if (valid) {
                    // 校验表单
                    _this.clicked = true;
                    this.form.targets = [];
                    this.form.status = 0;
                    if (this.form.dateTime.length > 0) {
                        this.form.beginDate = this.form.dateTime[0];
                        this.form.endDate = this.form.dateTime[1];
                    }
                    if (this.isProduct) {
                        this.form.amount = 0;
                    }

                  if (utils.isNull(this.form.productId)) {

                    this.$message.error('请选择活动商品');
                    return


                  }

                    if (this.vips.length > 0) {
                        this.vips.forEach((item) => {
                            let couponTarget = {
                                productType: 0,
                                targetId: item,
                                targetName: "",
                            };
                            if (item == 0) {
                                couponTarget.targetName = "vip1";
                            } else if (item == 1) {
                                couponTarget.targetName = "vip2";
                            } else if (item == 2) {
                                couponTarget.targetName = "vip3";
                            } else if (item == 3) {
                                couponTarget.targetName = "vip4";
                            } else if (item == 4) {
                                couponTarget.targetName = "vip5";
                            }
                            this.form.targets.push(couponTarget);
                        });
                    }
                    if (this.form.targetType == 5) {
                        this.form.type = 3;
                        this.form.mode = 1;
                    }
                    this.form.status = 0;
                    this.$delete(this.form,'dateTime')
                    update(_this.form)
                        .then((response) => {
                            console.log(response);
                            _this.clicked = false;
                            EventBus.$emit("exchange-edit", response.data);
                            _this.$store
                                .dispatch("tagsView/delView", _this.$route)
                                .then(({ visitedViews }) => {
                                    _this.$router.push({
                                        path: "/exchange/list",
                                    });
                                }); // 关闭当前tab回到列表
                        })
                        .catch((error) => {
                            _this.clicked = false;
                        });
                } else {
                    return false;
                }
            });
        },
    },
};
</script>
